package handlers

import (
	"collect-ease/Cache"
	"collect-ease/models"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var article []models.Article
	redis_key := "list_page_" + strconv.Itoa(page)
	cacheData, _ := Cache.Rdb.Get(Cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Debug().Find(&article)
		jsonData, _ := json.Marshal(article)
		Cache.Rdb.Set(Cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &article)
	}
	var total int64
	models.DB.Model(&models.Article{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  article,
		"total": total,
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var article models.Article
	redis_key := "detail_" + id
	cacheData, _ := Cache.Rdb.Get(Cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id=?", id).First(&article)
		jsonData, _ := json.Marshal(article)
		Cache.Rdb.Set(Cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &article)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": article,
	})
	return

}
